// 封装公共函数

// 格式化时间
export const formatTime = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
  if (!date) return '';
  
  if (typeof date === 'string') {
    date = new Date(date);
  }
  
  if (isNaN(date.getTime())) return '';
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds);
};

// 格式化距离现在的时间
export const formatRelativeTime = (date) => {
  if (!date) return '';
  
  if (typeof date === 'string') {
    date = new Date(date);
  }
  
  const now = new Date();
  const diff = now - date;
  
  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚';
  }
  
  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`;
  }
  
  // 小于24小时
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
  }
  
  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
  }
  
  // 其他情况返回具体日期
  return formatTime(date, 'YYYY-MM-DD');
};

// 存储用户信息
export const setUserInfo = (userInfo) => {
  try {
    uni.setStorageSync('userInfo', JSON.stringify(userInfo));
  } catch (e) {
    console.error('存储用户信息失败', e);
  }
};

// 获取用户信息
export const getUserInfo = () => {
  try {
    const userInfoStr = uni.getStorageSync('userInfo');
    return userInfoStr ? JSON.parse(userInfoStr) : null;
  } catch (e) {
    console.error('获取用户信息失败', e);
    return null;
  }
};

// 清除用户信息
export const clearUserInfo = () => {
  try {
    uni.removeStorageSync('userInfo');
    uni.removeStorageSync('token');
  } catch (e) {
    console.error('清除用户信息失败', e);
  }
};

// 存储token
export const setToken = (token) => {
  try {
    uni.setStorageSync('token', token);
  } catch (e) {
    console.error('存储token失败', e);
  }
};

// 获取token
export const getToken = () => {
  try {
    return uni.getStorageSync('token') || '';
  } catch (e) {
    console.error('获取token失败', e);
    return '';
  }
};

// 检查是否登录
export const isLoggedIn = () => {
  return !!getToken();
};

// 生成唯一ID
export const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

// 防抖函数
export const debounce = (func, wait) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

// 节流函数
export const throttle = (func, limit) => {
  let inThrottle;
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
};

// 深拷贝
export const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  
  if (obj instanceof Date) {
    return new Date(obj.getTime());
  }
  
  if (obj instanceof Array) {
    return obj.map(item => deepClone(item));
  }
  
  if (typeof obj === 'object') {
    const clonedObj = {};
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key]);
      }
    }
    return clonedObj;
  }
};

// 显示提示信息
export const showToast = (title, icon = 'none', duration = 2000) => {
  uni.showToast({
    title,
    icon,
    duration
  });
};

// 显示加载中
export const showLoading = (title = '加载中...') => {
  uni.showLoading({
    title,
    mask: true
  });
};

// 隐藏加载中
export const hideLoading = () => {
  uni.hideLoading();
};

// 获取随机颜色
export const getRandomColor = () => {
  const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9'];
  return colors[Math.floor(Math.random() * colors.length)];
};

// 数字格式化（如：1000 -> 1k）
export const formatNumber = (num) => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M';
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k';
  }
  return num.toString();
};

// 验证手机号
export const validatePhone = (phone) => {
  const reg = /^1[3-9]\d{9}$/;
  return reg.test(phone);
};

// 验证邮箱
export const validateEmail = (email) => {
  const reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return reg.test(email);
};

// 获取屏幕信息
export const getScreenInfo = () => {
  try {
    const { windowWidth, windowHeight } = uni.getSystemInfoSync();
    return {
      windowWidth,
      windowHeight
    };
  } catch (e) {
    console.error('获取屏幕信息失败', e);
    return {
      windowWidth: 375,
      windowHeight: 667
    };
  }
};

// 计算两点之间的距离
export const calculateDistance = (lat1, lon1, lat2, lon2) => {
  const R = 6371; // 地球半径（公里）
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLon = (lon2 - lon1) * Math.PI / 180;
  const a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
    Math.sin(dLon/2) * Math.sin(dLon/2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  const distance = R * c;
  return distance;
};

// 生成漂流瓶内容模板
export const getBottleTemplates = () => {
  return [
    '我在{{planet}}留下了我的思念...',
    '来自{{planet}}的问候，愿你一切安好！',
    '星空如此浩瀚，我在这里思考着生命的意义...',
    '希望这个漂流瓶能带给你好运和快乐！',
    '在这颗蓝色星球上，我想对你说...',
    '宇宙那么大，我们却相遇了，这是多么奇妙的缘分！'
  ];
};

export default {
  formatTime,
  formatRelativeTime,
  setUserInfo,
  getUserInfo,
  clearUserInfo,
  setToken,
  getToken,
  isLoggedIn,
  generateId,
  debounce,
  throttle,
  deepClone,
  showToast,
  showLoading,
  hideLoading,
  getRandomColor,
  formatNumber,
  validatePhone,
  validateEmail,
  getScreenInfo,
  calculateDistance,
  getBottleTemplates
};